package com.xlz.system.shiro;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.xlz.common.config.ApplicationContextRegister;
import com.xlz.common.datasource.DatabaseContextHolder;
import com.xlz.common.datasource.DatabaseType;
import com.xlz.common.utils.ShiroUtils;
import com.xlz.system.dao.UserDao;
import com.xlz.system.domain.UserDO;
import com.xlz.system.service.MenuService;
/**
 * @author 张蕾蕾
 * @date 2018 03 24
 */
public class UserRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		DatabaseType defaultDataSource = DatabaseContextHolder.getDatabaseType();
		DatabaseContextHolder.setDatabaseType(DatabaseType.system);
		Long userId = ShiroUtils.getUserId();
		MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		DatabaseContextHolder.setDatabaseType(defaultDataSource);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Map<String, Object> map = new HashMap<>(16);
		map.put("username", username);
		String password = new String((char[]) token.getCredentials());

		UserDao userMapper = ApplicationContextRegister.getBean(UserDao.class);
		// 查询用户信息
		UserDO user = userMapper.list(map).get(0);

		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException("账号或密码不正确");
		}

		// 密码错误
		if (!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确");
		}

		// 账号锁定
		if (user.getStatus() == 0) {
			throw new LockedAccountException("账号已被锁定,请联系管理员");
		}
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
		return info;
	}

	public void reloadAuthorizing(String username){  
        Subject subject = SecurityUtils.getSubject();   
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();   
        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户   
        SimplePrincipalCollection principals = new SimplePrincipalCollection(username,realmName);   
        subject.runAs(principals);   
        this.getAuthorizationCache().remove(subject.getPrincipals());   
        subject.releaseRunAs();  
    } 
	/** 
	 * 清空所有关联认证 
	 */  
	public void clearAllCachedAuthorizationInfo2() {  
	    Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();  
	    if (cache != null) {  
	        for (Object key : cache.keys()) {  
	            System.out.println(key+":"+key.toString());  
	            cache.remove(key);  
	        }  
	    }  
	}
}
